using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Utilities
{
    /// <summary>
    /// 
    /// </summary>
    public class Base64Util
    {
        #region encode
        /// <summary></summary>
        public static string EncodeAsBase64(string input, bool swap)
        {
            if (string.IsNullOrEmpty(input))
            {
                input = string.Empty;
            }
            else if(swap)
            {
                byte[] bytes = System.Text.Encoding.Default.GetBytes(input);
                input = System.Text.Encoding.Default.GetString(Base64Util.SwapBytes(bytes));
            }
            string output = System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(input));
            return output;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string EncodeAsBase64(byte[] bytes)
        {
            return System.Convert.ToBase64String(bytes);
        }
        #endregion

        #region decode
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="swap"></param>
        /// <returns></returns>
        public static string DecodeAsString(string input, bool swap)
        {
            string plainStr = System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(input));
            if (swap)
            {
                byte[] bytes = System.Text.Encoding.Default.GetBytes(plainStr);
                plainStr = System.Text.Encoding.Default.GetString(Base64Util.SwapBytes(bytes));
            }
            return plainStr;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static byte[] DecodeAsBytes(string input)
        {
            return System.Convert.FromBase64String(input);
        }
        #endregion

        #region byte-swap
        private static byte[] SwapBytes(byte[] input)
        {
            if (input != null && input.Length > 0)
            {
                byte[] output = new byte[input.Length];
                for (int i = input.Length - 1; i >= 0; i--)
                {
                    output[input.Length - i - 1] = input[i];
                }
                return output;
            }
            else
            {
                return null;
            }
        }
        #endregion
    }
}
